package org.csu.mypetstore.web.servlet;

import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

public class CartChangeServlet extends HttpServlet {

    private Cart cart;
    private Iterator<CartItem> cartItemIterator;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        cart = (Cart) session.getAttribute("cart");
        cartItemIterator = cart.getAllCartItems();
        CartItem item = new CartItem();
        while (cartItemIterator.hasNext()) {
            CartItem cartItem = cartItemIterator.next();
            String itemId = cartItem.getItem().getItemId();

            int quantity = Integer.parseInt((String)req.getParameter("quantity"));
            if (quantity != cartItem.getQuantity()) {
                item.setQuantity(quantity);
                item.setItem(cartItem.getItem());
                cart.setQuantityByItemId(itemId,quantity);
                item.setTotal(cartItem.getTotal());
            }

            if (quantity < 1) {
                cartItemIterator.remove();
            }
        }

        session.setAttribute("cart",cart);

        Cart cart1 = (Cart) session.getAttribute("cart");
        Iterator<CartItem> cartItemIterator1 = cart1.getAllCartItems();
        String quantityAll = "";
        quantityAll += item.getQuantity() + "," + item.getTotal() + "," + cart1.getSubTotal()+",";

        resp.setContentType("text/plain");
        PrintWriter out =  resp.getWriter();
        out.print(quantityAll);
        out.flush();
        out.close();
    }
}